package com.pet.serve.controller;

import com.pet.serve.entity.Customers;
import com.pet.serve.config.JwtTokenUtil;
import com.pet.serve.exception.ResourceNotFoundException;
import com.pet.serve.repository.CustomerRepository;
import com.pet.serve.request.LoginRequest;
import com.pet.serve.response.ApiResponse;
import com.pet.serve.service.CustomerService;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class CustomerController {

    // 注入 JwtTokenUtil 实例
    private final JwtTokenUtil jwtTokenUtil;

    @Autowired
    public CustomerController(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerRepository customerRepository;


    // 获取所有客户
    @GetMapping("/user/getAll")
    public ResponseEntity<ApiResponse> getAllCustomers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String permission,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date regdayStart,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date regdayEnd,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthdayStart,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthdayEnd,
            @RequestParam("pageNo") int pageNo,
            @RequestParam("pageSize") int pageSize) {

        List<Customers> customers;
        if (!StringUtils.isEmpty(name)) {
            customers = customerService.getCustomerByName(name, pageNo, pageSize);
        } else if (permission != null && !permission.isEmpty()) {
            Customers.UserRole userRole = Customers.UserRole.valueOf(permission);
            customers = customerService.getCustomerByPermission(userRole, pageNo, pageSize);
        } else if (regdayStart != null && regdayEnd != null) {
            customers = customerService.getCustomerByRegday(regdayStart, regdayEnd, pageNo, pageSize);
        } else if (birthdayStart != null && birthdayEnd != null) {
            customers = customerService.getCustomerByBirthday(birthdayStart, birthdayEnd, pageNo, pageSize);
        } else {
            customers = customerService.getAllCustomers(pageNo, pageSize);
        }

        return ResponseEntity.ok(new ApiResponse(true, "获取成功", customers, customers.size()));

    }


    // 通过ID获取客户
    @GetMapping("/user/{id}")
    public ResponseEntity<Customers> getCustomerById(@PathVariable Long id) {
        Customers customer = customerService.getCustomerById(id);
        if (customer != null) {
            return ResponseEntity.ok(customer);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        try {
            String username = loginRequest.getUsername();
            String password = loginRequest.getPassword();
            boolean isAuthenticated = customerService.authenticate(username, password);

            if (isAuthenticated) {
                String token = jwtTokenUtil.generateToken(username);
                Customers user = customerService.findByUsername(username);
                // 将用户信息放入 data 字段
                return ResponseEntity.ok(new ApiResponse(true, "登录成功", user, token));
            } else {
                return ResponseEntity.ok(new ApiResponse(false, "用户名或密码错误", null, null)); // 错误信息保持一致
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "服务器内部错误: " + e.getMessage(), null, null));
        }
    }

    // 注册客户
    @PostMapping("/user/register")
    public ResponseEntity<String> registerCustomer(@RequestBody Customers customer) {
        boolean result = customerService.registerCustomer(customer);
        if (result) {
            return ResponseEntity.ok("注册成功");
        } else {
            return ResponseEntity.badRequest().body("用户名已存在");
        }
    }

    @GetMapping("/user/get")
    public ResponseEntity<ApiResponse> getUserByUsername(@RequestHeader("Authorization") String token) {
        // 检查 token 格式并提取用户名
        if (token != null && token.startsWith("Bearer ")) {
            String username = jwtTokenUtil.getUsernameFromToken(token.substring(7));
            System.out.println("get的用户名: " + username);
            Customers customer = customerService.getCustomerByUsername(username);
            if (customer != null) {
                return ResponseEntity.ok(new ApiResponse(true, "用户信息获取成功", customer,token));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse(false, "用户未找到", null));
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ApiResponse(false, "未授权", null));
        }
    }


    // 更新客户信息
    @PutMapping("/user/update")
    public ResponseEntity<ApiResponse> updateCustomer(@RequestBody Customers customer) {
        Customers existingCustomer;

        // 检查 id 和 username
        if (customer.getId() != null) {
            // 如果 id 不为空，使用 id 查询
            existingCustomer = customerRepository.findById(customer.getId())
                    .orElseThrow(() -> new ResourceNotFoundException("用户未找到"));
        } else if (customer.getUsername() != null && !customer.getUsername().isEmpty()) {
            // 如果 id 为空但 username 不为空，使用 username 查询
            existingCustomer = customerRepository.findByUsername(customer.getUsername())
                    .orElseThrow(() -> new ResourceNotFoundException("用户未找到"));
        } else {
            // 如果 id 和 username 都为空，返回错误
            return ResponseEntity.badRequest().body(new ApiResponse(false, "id 和 username 不能同时为空"));
        }

        // 更新其他字段
        existingCustomer.setNickname(customer.getNickname());
        existingCustomer.setName(customer.getName());
        existingCustomer.setSex(customer.getSex());
        existingCustomer.setBirthday(customer.getBirthday());
        existingCustomer.setPermission(customer.getPermission());
        existingCustomer.setLevel(customer.getLevel());
        existingCustomer.setMoney(customer.getMoney());
        // 不更新密码

        customerService.addOrUpdateCustomer(existingCustomer);
        return ResponseEntity.ok(new ApiResponse(true, "用户信息更新成功"));
    }



    // 删除客户
    @DeleteMapping("/user/delete")
    public ResponseEntity<ApiResponse> deleteCustomer(@RequestBody List<String> usernames) {
        for (String username : usernames) {
            customerService.deleteCustomerByUsername(username);
        }
        return ResponseEntity.ok(new ApiResponse(true, "Users deleted successfully"));
    }

    // 验证原密码
    @PostMapping("/user/check/psd")
    public ResponseEntity<ApiResponse> checkPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String oldPassword = request.get("psd");

        // 验证用户名和密码
        boolean isValid = customerService.validatePassword(username, oldPassword);

        if (isValid) {
            return ResponseEntity.ok(new ApiResponse(true, "密码验证成功"));
        } else {
            return ResponseEntity.ok(new ApiResponse(false, "原密码不正确"));
        }
    }

    // 更新密码
    @PutMapping("/user/update/psd")
    public ResponseEntity<ApiResponse> updatePassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String newPassword = request.get("psd");

        // 更新用户密码
        boolean updated = customerService.updatePassword(username, newPassword);

        if (updated) {
            return ResponseEntity.ok(new ApiResponse(true, "密码修改成功"));
        } else {
            return ResponseEntity.ok(new ApiResponse(false, "密码修改失败"));
        }
    }


    // 修改密码
    @PutMapping("/updatePassword")
    public ResponseEntity<String> updatePassword(@RequestParam String username, @RequestParam String oldPassword, @RequestParam String newPassword) {
        boolean success = customerService.updatePassword(username, oldPassword, newPassword);
        if (success) {
            return ResponseEntity.ok("密码修改成功");
        } else {
            return ResponseEntity.badRequest().body("旧密码不正确");
        }
    }

    // 重置密码
    @PutMapping("/user/resetPassword")
    public ResponseEntity<ApiResponse> resetPassword(@RequestBody Map<String, String> payload) {
        String username = payload.get("username");
        String newPassword = payload.get("newPassword");
        boolean success = customerService.resetPassword(username, newPassword);
        if (success) {
            return ResponseEntity.ok(new ApiResponse(true, "密码重置成功"));
        } else {
            return ResponseEntity.badRequest().body(new ApiResponse(false, "用户不存在"));
        }
    }


    // 删除管理员
    @DeleteMapping("/deleteAdmin")
    public ResponseEntity<Void> deleteAdmin(@RequestParam String username) {
        customerService.deleteAdminByUsername(username);
        return ResponseEntity.noContent().build();
    }

    // 添加用户
    @PostMapping("user/add")
    public  ResponseEntity<ApiResponse> addCustomer(@RequestBody Customers customer) {
        boolean result = customerService.registerCustomer(customer);
        if (result) {
            return ResponseEntity.ok(new ApiResponse(true, "添加成功"));
        } else {
            return ResponseEntity.badRequest().body(new ApiResponse(false, "用户名已存在"));
        }
    }

}

